


/**
* 属性
* + options
* + data 记录当前route数据 响应方式的
* + routeMap
* 方法
* + Constructor(Options): VueRouter
* _install(Vue):void
* + init():void
* + initEvent():void
* + createRouteMap():void
* + initComponents(Vue):void
*/

let _Vue = null

export default class VueRouter {
  static install (Vue) {
    // 判断当前插件是否被安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 把vue的构造函数记录到全局变量
    _Vue = Vue
    // 创建Vue实例时候注入router对象到vue实例上
    // 混入
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
         }
      }
    })
  }
  constructor (options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      current: window.location.pathname
    })
  }
  isHash = () => {
    console.log(this.options.mode)
    return String(this.options.mode).toLowerCase() === 'hash'
  }
  init () {
    this.createRouteMap( )
    this.initComponents(_Vue)
    this.initEvent()
  }
  createRouteMap () {
    // 遍历所有的路由规则 储存到routeMap {path: components}
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }
  initEvent () {
    if (this.isHash()) {
      window.addEventListener('hashchange', (e) => {
        console.log(e)
        // this.data.current = window.location.pathname
      })
    } else {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    }
    
  }
  initComponents (Vue) {
    const that = this
    // 生成<router-link/>
    Vue.component('router-link',{
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render (h) {
        return h('a', {
          attrs: {
            href: (that.isHash() ? '/#' : '') + this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          that.isHash() ? location.href = '/#' + this.to : history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })

    // 生成<router-view>
    const self = this
    Vue.component('router-view', {
      render (h) {
        const components = self.routeMap[self.data.current]
        return h(components)
      }
    })
  }
}
